//
//  MCategoryBLL.m
//  LZMusicPlayer
//
//  Created by wulanzhou on 2016/11/9.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "MCategoryBLL.h"
#import "CacheDataUtil.h"
#import "BMATag.h"

#define kCacheTagKeyList @"kCacheTagKeyList"
#define kCacheALLTagList @"kCacheALLTagList"

@interface MCategoryBLL () {
    
    NSArray *_tagKeyList;
    NSDictionary *_allTagList;
}

@end

@implementation MCategoryBLL

@synthesize tagList = _tagKeyList;
@synthesize categoryList = _allTagList;

- (NSArray *)tagList{
    
    if (!_tagKeyList) {
        _tagKeyList=[CacheDataUtil unarchiveValueForKey:kCacheTagKeyList];
    }
    return _tagKeyList;
}

- (NSDictionary *)categoryList{
    
    if (!_allTagList) {
        _allTagList=[CacheDataUtil unarchiveValueForKey:kCacheALLTagList];
    }
    return _allTagList;
}

- (void)loadCategory:(void (^) ())completion{

    BMATag *request = [[BMATag alloc] init];
    __weak BMATag *WSELF = request;
    [request setCZRequestURL:^NSString *{
        return [WSELF allSongTags];
    }];
    [request starWithFinishedBlock:^(NSError *error, id result) {
        if (!error) {
            
            _tagKeyList = result[@"tags"];
            
            [CacheDataUtil setValueArchiver:_tagKeyList forKey:kCacheTagKeyList];
            
            NSDictionary *allList = result[@"taglist"];
            __block NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
            [_tagKeyList enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
                
                NSArray *arr = [allList[key] valueForKeyPath:@"title"];
                if (arr&&[arr count]>0) {
                    NSMutableArray *source = [NSMutableArray arrayWithCapacity:0];
                    [source addObject:key];
                    [source addObjectsFromArray:arr];
                    
                    [dic setValue:source forKey:key];
                }
            }];
            
            _allTagList = dic;
            
            //NSLog(@"_allTagList =%@",_allTagList);
            [CacheDataUtil setValueArchiver:_allTagList forKey:kCacheALLTagList];
        }
        
        if (completion) {
            completion ();
        }
    }];
}

@end
